﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Data;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Visifire.Charts;
using Microsoft.Windows.Controls.Primitives;
using Microsoft.Win32;


using Negocio;

namespace Presentacion
{
    public partial class WGroupReport
    {
        private DataTable table;
        private RenderAs chartType;
        private Title chartTitle;
        private Chart visiChart;
 
        public WGroupReport()
        {
            this.InitializeComponent();
            chartTitle = new Title();
            loadCbxChartTypes();
            chartType = RenderAs.Column;
            chartTitle = new Title();
            dpDate.SelectedDate = DateTime.Today;
            table = new DataTable();
            cbxGroup.ItemsSource = Club.getInstance().Groups;
            cbxEvaluation.ItemsSource = Club.getInstance().Evaluations;
            // Insert code required on object creation below this point.
        }

        private void cbxGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxGroup.SelectedIndex != -1 && cbxEvaluation.SelectedIndex != -1)
            {
                loadTable(Club.getInstance().evaluationsOfGroupInADate((Group)cbxGroup.SelectedItem, (Evaluation)cbxEvaluation.SelectedItem, dpDate.SelectedDate.Value));
            }
        }

        private void cbxEvaluation_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxGroup.SelectedIndex != -1 && cbxEvaluation.SelectedIndex != -1)
            {
                loadTable(Club.getInstance().evaluationsOfGroupInADate((Group)cbxGroup.SelectedItem, (Evaluation)cbxEvaluation.SelectedItem, dpDate.SelectedDate.Value));
            }
        }

        private void dpDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxGroup.SelectedIndex != -1 && cbxEvaluation.SelectedIndex != -1)
            {
                loadTable(Club.getInstance().evaluationsOfGroupInADate((Group)cbxGroup.SelectedItem, (Evaluation)cbxEvaluation.SelectedItem, dpDate.SelectedDate.Value));
            }
        }
        private void loadTable(ObservableCollection<PlayerExecution> execList)
        {
            table.Clear();
            table.Columns.Clear();
            dataGrid1.ItemsSource = null;
            IEnumerator<PlayerExecution> plyexec = execList.GetEnumerator();
            DataColumn colGraf = new DataColumn("Graficar", typeof(bool));
            table.Columns.Add(colGraf);
            DataColumn colJug = new DataColumn("Jugador", typeof(string));
            table.Columns.Add(colJug);
            colJug.ReadOnly = true;
            bool columnsComplete = false;
            while (plyexec.MoveNext())
            {
                IEnumerator<TestValue> p = plyexec.Current.Values.GetEnumerator();
                while (p.MoveNext() && columnsComplete == false)
                {
                    DataColumn colTest = new DataColumn(p.Current.Test.Name, typeof(float));
                    colTest.ReadOnly = true;
                    table.Columns.Add(colTest);
                }
                columnsComplete = true;
                p.Reset();
                DataRow row = table.NewRow();
                while (p.MoveNext())
                {

                    row["Jugador"] = plyexec.Current.Player.CompleteName;
                    row[p.Current.Test.Name] = p.Current.ValueExecution;
                    row["Graficar"] = false;
                }
                table.Rows.Add(row);
                p.Reset();
            }
            dataGrid1.FrozenColumnCount = 1;
            dataGrid1.ItemsSource = table.DefaultView;
        }

        private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //visiChart = new Chart();
            //try
            //{
            //    for (int j= 0; j < table.Rows.Count; j++)
            //    {
            //        DataSeries ds = new DataSeries();
            //        if (table.Rows[j]["Graficar"].ToString().Equals("True"))
            //        {
            //            for (int i = 2; i < table.Columns.Count; i++)
            //            {
            //                DataPoint dp = new DataPoint();
            //                dp.YValue = Double.Parse(table.Rows[j][table.Columns[i].ColumnName].ToString());
            //                dp.AxisXLabel = table.Columns[i].ColumnName;
            //                dp.XValue = null;
            //                ds.DataPoints.Add(dp);
            //            }
            //            string [] dsName=table.Rows[j]["Jugador"].ToString().Split(',');
            //            string []name = dsName[0].Split(' ');
            //            ds.Name =name[0]+name[1];
            //            loadChart(ds);
            //        }
            //    }
            //}
            //catch (Exception)
            //{

            //}
        }

        public void loadChart(DataSeries ds)
        {
            visiChart.Titles.Clear();
            visiChart.Titles.Add(chartTitle);
            ds.RenderAs = chartType;
            visiChart.Width = gridChart.Width; // Width and Height are required for the Chart.
            visiChart.Height = gridChart.Height;
            visiChart.Series.Add(ds);
            gridChart.Children.Clear(); // So that Chart objects don't build up each time we add one.
            gridChart.Children.Add(visiChart);
           

        }

        private void dataGrid1_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            visiChart = new Chart();
            DependencyObject dep = (DependencyObject)e.OriginalSource;

            // iteratively traverse the visual tree
            while ((dep != null) && !(dep is DataGridColumnHeader))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }

            if (dep == null)
                return;

            if (dep is DataGridColumnHeader)
            {
                DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;
                chartTitle.Text = columnHeader.Column.Header.ToString();
                if (!(columnHeader.Column.Header.Equals("Jugador") || columnHeader.Column.Header.Equals("Graficar")))
                {
                    DataSeries ds = new DataSeries();
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        DataPoint dp = new DataPoint();
                        dp.YValue = Double.Parse(table.Rows[i][columnHeader.Column.Header.ToString()].ToString());
                        dp.AxisXLabel = table.Rows[i]["Jugador"].ToString();
                        dp.XValue = null;
                        ds.DataPoints.Add(dp);
                    }
                    loadChart(ds);
                }
            }

            
        }
        private void loadCbxChartTypes()
        {
            IList<RenderAs> chartTypes = new List<RenderAs>();
            chartTypes.Add(RenderAs.Area);
            chartTypes.Add(RenderAs.Bar);
            chartTypes.Add(RenderAs.Bubble);
            chartTypes.Add(RenderAs.Column);
            chartTypes.Add(RenderAs.Doughnut);
            chartTypes.Add(RenderAs.Line);
            chartTypes.Add(RenderAs.Pie);
            chartTypes.Add(RenderAs.Point);
            chartTypes.Add(RenderAs.StackedArea);
            chartTypes.Add(RenderAs.StackedArea100);
            chartTypes.Add(RenderAs.StackedBar);
            chartTypes.Add(RenderAs.StackedBar100);
            chartTypes.Add(RenderAs.StackedColumn);
            chartTypes.Add(RenderAs.StackedColumn100);
            cbxChartType.ItemsSource = chartTypes;
        }

        private void cbxChartType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxChartType.SelectedIndex != -1)
            {
                chartTitle.Text = cbxEvaluation.Text;
                chartType = (RenderAs)cbxChartType.SelectedItem;
                //dataGrid1_SelectionChanged(sender, e);
                visiChart = new Chart();
                //visiChart.Titles.Clear();
                //visiChart.Titles.Add(chartTitle);
                try
                {
                    for (int j = 0; j < table.Rows.Count; j++)
                    {
                        DataSeries ds = new DataSeries();
                        if (table.Rows[j]["Graficar"].ToString().Equals("True"))
                        {
                            for (int i = 2; i < table.Columns.Count; i++)
                            {
                                DataPoint dp = new DataPoint();
                                dp.YValue = Double.Parse(table.Rows[j][table.Columns[i].ColumnName].ToString());
                                dp.AxisXLabel = table.Columns[i].ColumnName;
                                dp.XValue = null;
                                ds.DataPoints.Add(dp);
                            }
                            string[] dsName = table.Rows[j]["Jugador"].ToString().Split(',');
                            string[] name = dsName[0].Split(' ');
                            ds.Name = name[0] + name[1];
                            loadChart(ds);
                        }
                    }
                   
                }
                catch (Exception)
                {

                }
                cbxChartType.SelectedIndex = -1;
            }
        }

        private void gridChart_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            DependencyObject dep = (DependencyObject)e.OriginalSource;

            while ((dep != null) && !(dep is Chart))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }
            if (dep is Chart)
            {
                Chart cell = new Chart();
                cell = dep as Chart;
                visiChart = new Chart();
                string[] toolTip = cell.ToolTips[0].Text.Split(',');
                string xValue = toolTip[0];
                for (int j = 0; j < cell.Series.Count; j++)
                {
                    DataSeries ds = new DataSeries();
                    for (int i = 0; i < cell.Series[j].DataPoints.Count; i++)
                    {
                        if (!(cell.Series[j].DataPoints[i].AxisXLabel.Equals(xValue)))
                        {
                            DataPoint dp = new DataPoint();
                            dp.YValue = cell.Series[j].DataPoints[i].YValue;
                            dp.XValue = null;
                            dp.AxisXLabel = cell.Series[j].DataPoints[i].AxisXLabel;
                            ds.DataPoints.Add(dp);
                        }
                    }
                    string[] dsName = table.Rows[j]["Jugador"].ToString().Split(',');
                    string[] name = dsName[0].Split(' ');
                    ds.Name = name[0] + name[1];
                    loadChart(ds);
                }
            }
        }

        private void DataGrid_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            //visiChart = new Chart();
            //try
            //{
            //    for (int j = 0; j < table.Rows.Count; j++)
            //    {
            //        DataSeries ds = new DataSeries();
            //        if (table.Rows[j]["Graficar"].ToString().Equals("True"))
            //        {
            //            for (int i = 2; i < table.Columns.Count; i++)
            //            {
            //                DataPoint dp = new DataPoint();
            //                dp.YValue = Double.Parse(table.Rows[j][table.Columns[i].ColumnName].ToString());
            //                dp.AxisXLabel = table.Columns[i].ColumnName;
            //                dp.XValue = null;
            //                ds.DataPoints.Add(dp);
            //            }
            //            string[] dsName = table.Rows[j]["Jugador"].ToString().Split(',');
            //            ds.Name = dsName[1].Trim();
            //            loadChart(ds);
            //        }
            //        chartTitle.Text = cbxEvaluation.Text + "," + cbxGroup.Text;
            //    }
            //}
            //catch (Exception)
            //{

            //}
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog v = new SaveFileDialog();
            v.Filter = "Excel(*.csv)|*.csv|Todos los Archivos(*.*)|*.*";
            v.AddExtension = true;
            v.DefaultExt = ".csv";
            bool yes = v.ShowDialog().Value;
            if (yes)
            {
                try
                {
                    if (cbxGroup.SelectedIndex != -1 && cbxEvaluation.SelectedIndex != -1)
                    {
                        string evaluationGroupName = this.cbxEvaluation.Text + "," + this.cbxGroup.Text;                        
                        Club.getInstance().writePlayersExecutionToFile(dpDate.SelectedDate.Value, evaluationGroupName, v.FileName);
                    }                    
                }
                catch (ArgumentOutOfRangeException)
                {
                    MessageBox.Show("Seleccione un archivo válido", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                catch (IndexOutOfRangeException)
                {
                    MessageBox.Show("Seleccione un archivo válido", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog printDialog = new PrintDialog();
            Nullable<Boolean> print = printDialog.ShowDialog();
            if (print == true)
            {
                this.btnExport.Visibility = Visibility.Collapsed;
                this.btnPrint.Visibility = Visibility.Collapsed;
                this.cbxChartType.Visibility = Visibility.Collapsed;
                printDialog.PrintVisual(LayoutRoot, "Reporte Grupal");
                this.btnExport.Visibility = Visibility.Visible;
                this.btnPrint.Visibility = Visibility.Visible;
                this.cbxChartType.Visibility = Visibility.Visible;
            }
        }
    }
}